﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WLFramework.DataAccess;
using WLFramework.Json;

namespace SampleSite.ajax
{
    /// <summary>
    /// GetTreeNodes1 的摘要说明
    /// </summary>
    public class GetTreeNodes1 : IHttpHandler
    {

        private class TreeNode
        {
            public int id { get; set; }
            public string text { get; set; }
            public List<TreeNode> children { get; set; }
        }

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                context.Response.ContentType = "text/plain";
                PermissionCommand command = DataAccessor.CreateInstance<PermissionCommand>();
                var list = command.SYS_GetOrg().ToList();

                List<TreeNode> nodes = new List<TreeNode>();
                int depths = list.Max(k => k.Depth) + 1;
                Dictionary<int, TreeNode> parents = null;
                Dictionary<int, TreeNode> currents = null;
                for (int i = 0; i < depths; i++)
                {
                    int j = 0;
                    currents = new Dictionary<int, TreeNode>();
                    while (j < list.Count)
                    {
                        if (i == list[j].Depth)
                        {
                            TreeNode node = new TreeNode()
                            {
                                id = list[j].O_ID,
                                text = list[j].O_CName,
                                children = new List<TreeNode>()
                            };

                            if (list[j].Depth == 0)
                            {
                                nodes.Add(node);
                            }

                            currents[node.id] = node;

                            if (list[j].O_ParentID > 0 &&
                                parents != null &&
                                parents.ContainsKey(list[j].O_ParentID.Value))
                            {
                                parents[list[j].O_ParentID.Value].children.Add(node);
                            }

                            list.RemoveAt(j);
                        }
                        else
                        {
                            j++;
                        }
                    }

                    parents = currents;
                    currents = null;
                }

                context.Response.Write(JSON.Instance.ToJSON(nodes));
            }
            catch (Exception ex)
            {
                context.Response.Write(ex.Message);
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}